// Cookie polyfill - 确保 Cookies 对象在所有环境下都可用
import Cookies from 'js-cookie';

// 简单的 Cookie polyfill 实现
const cookiePolyfill = {
  get: (name: string) => {
    try {
      return Cookies.get(name);
    } catch {
      // 如果 js-cookie 不可用，使用原生实现
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) {
        return parts.pop()?.split(';').shift();
      }
      return undefined;
    }
  },
  
  set: (name: string, value: string, options?: any) => {
    try {
      return Cookies.set(name, value, options);
    } catch {
      // 如果 js-cookie 不可用，使用原生实现
      let cookieString = `${name}=${value}`;
      if (options?.expires) {
        cookieString += `; expires=${new Date(Date.now() + options.expires * 24 * 60 * 60 * 1000).toUTCString()}`;
      }
      if (options?.path) {
        cookieString += `; path=${options.path}`;
      }
      document.cookie = cookieString;
    }
  },
  
  remove: (name: string, options?: any) => {
    try {
      return Cookies.remove(name, options);
    } catch {
      // 如果 js-cookie 不可用，使用原生实现
      let cookieString = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
      if (options?.path) {
        cookieString += `; path=${options.path}`;
      }
      document.cookie = cookieString;
    }
  }
};

// 确保全局 Cookies 对象可用
if (typeof window !== 'undefined') {
  // 优先使用 js-cookie，如果不可用则使用 polyfill
  (window as any).Cookies = (window as any).Cookies || Cookies || cookiePolyfill;
  
  console.log('🍪 Cookie 支持状态:', {
    nativeCookies: typeof Cookies !== 'undefined',
    windowCookies: typeof (window as any).Cookies !== 'undefined',
    documentCookie: typeof document.cookie !== 'undefined'
  });
}

export default cookiePolyfill; 